package cn.dlc.com.handler;

import cn.dlc.com.utils.JsonUtils;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * 登录校验，拦截登录之前的操作，先到BasicAuthenticationFilter，然后到这个方法，
 */
@Component
public class SystemAuthenticationEntryPoint implements AuthenticationEntryPoint {

	@Override
	public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {

		response.setContentType("application/json;charset=UTF-8");
		response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

		PrintWriter writer = response.getWriter();

		Map<String,Object> map = new HashMap<>();
		map.put("code",HttpServletResponse.SC_FORBIDDEN);
		map.put("msg","请登录");
		writer.write(JsonUtils.toString(map));
		writer.flush();
		writer.close();
	}
}
